<template>
	<view
		scroll-y="true" 
		:class="view"
		class="wrap" 
		@tap="onTap"
		@scroll="scrollmore"
		@scrolltoupper="refresh"
		@touchstart="handletouchstart"
		@touchmove="handletouchmove"
		@touchend="handletouchend"
		upper-threshold='-50'
		:scroll-into-view="toView">
		
		
		
		
		
		
		<view class="message" v-for="item in chatMsgStorage" >
			<view class="main" :class="item.style">
				<view class="user">
					11 {{item.style}}
					<text class="user-text">{{ item.name + ' ' + item.time}}</text>
				</view>
				<image class="avatar" :src="item.newAvatarUrl||item.avatarUrl||'/static/allAvatar.png'" :key="item.mid" :id="item.mid" @tap='openCard' :data-id="item.id"/>
				<view class="msg"> 
					<image
					class="err" :class="(item.style == 'self' && item.isFail) ?  'show' : 'hide'"
					src="/static/huanxin/images/msgerr.png"/>
			
					<image v-if="item.style == 'self'" src="/static/huanxin/images/poprightarrow@2x.png" class="msg_poprightarrow"/>
					<image v-if="item.style == ''" src="/static/huanxin/images/popleftarrow@2x.png" class="msg_popleftarrow"/>
					<view v-if="item.msg.type == 'img' || item.msg.type == 'video'">
						
						
						<image  v-if="item.msg.type == 'img'"
								class="avatar"
								:src="item.msg.data"
								style="width:90px; height:120px; margin:2px auto;"
								mode="aspectFit"
								@tap="previewImage"
								:data-url="item.msg.data" />
						<video v-if="item.msg.type == 'video'" :src="item.msg.data" controls autoplay />
					</view>
					<audio-msg
						v-if="item.msg.type == 'audio'"
						:msg="item"></audio-msg>
					<view v-else-if="item.msg.type == 'txt' || item.msg.type == 'emoji'">
						<view class="template" v-for="(d_item, d_index) in item.msg.data" :key="d_index" style="display: inline;">
							<text v-if="d_item.type == 'txt'"  class="msg-text" style="float:left;" @tap='goMap' :data-address="item.location.addr" :data-latitude="item.location.lat" :data-longitude="item.location.lng">{{ d_item.data }}</text>
							
							<image  v-if="d_item.type == 'emoji'"
									class="avatar"
									:src="'/static/huanxin/images/faces/' + d_item.data"
									style="width:25px; height:25px; margin:0 0 2px 0; float:left;" />
							
						</view>
						
					</view>
				
					
				</view>
			</view>
		</view>
		
		
		
		
		
		<view class="message" v-for="item in chatMsg" style="width: 92%;height: auto;padding: 0 30rpx;position: relative;">
			
			<view class="main" :class="item.style" style="width: 100%;height: 100%;" :style="item.style=='self'?'text-align: right;':''">
				<view class="user" style="position: relative;bottom: -30rpx;">
					<text class="user-text" style="margin: auto 100rpx 8rpx;font-size: 20rpx;color: #dcdcdc;display: block;">{{ item.name + ' ' + item.time}}</text>
				</view>
				
				<image class="avatar" :src="item.newAvatarUrl||item.avatarUrl||'/static/allAvatar.png'" :key="item.mid" :id="item.mid" @tap='openCard' :data-id="item.id" style="float: right;margin: 0 0 0 20rpx;width: 72rpx;height: 72rpx;margin: 0 20rpx 0 0;border-radius: 8rpx;float: left;" :style="item.style=='self'?'float: right;margin: 0 0 0 20rpx;':''"/>
				<view class="msg" style="display: inline-block;padding: 20rpx;max-width: calc(85% - 80rpx);min-height: 40rpx;font-size: 24rpx;text-align: left;word-break: break-all;background-color: #fff;border-radius: 26rpx;position: relative;margin-top: 24rpx;" :style="item.style=='self'?'background-color: #96ED6A;color: #fff;':''"> 
					<image
					class="err" :class="(item.style == 'self' && item.isFail) ?  'show' : 'hide'"
					src="/static/huanxin/images/msgerr.png" style="width: 32rpx;height: 32rpx;position: absolute;left: -40rpx;"/>
	
					<image v-if="item.style == 'self'" src="/static/huanxin/images/poprightarrow@2x.png" class="msg_poprightarrow" style="position: absolute;right: -10rpx;height: 18rpx;width: 18rpx;margin-top: -10rpx;"/>
					<image v-if="item.style == ''" src="/static/huanxin/images/popleftarrow@2x.png" class="msg_popleftarrow" style="position:absolute;left: -14rpx;height: 18rpx;width: 18rpx;margin-top: -10rpx;"/>
					<view v-if="item.msg.type == 'img' || item.msg.type == 'video'">
						
						 
						<image  v-if="item.msg.type == 'img'"
								class="avatar"
								:src="item.msg.data"
								style="width:90px; height:120px; margin:2px auto;"
								mode="aspectFit"
								@tap="previewImage"
								:data-url="item.msg.data" />
						<video v-if="item.msg.type == 'video'" :src="item.msg.data" controls autoplay />
					</view>
					<audio-msg
						v-if="item.msg.type == 'audio'"
						:msg="item"></audio-msg>
					<view v-else-if="item.msg.type == 'txt' || item.msg.type == 'emoji'">
						<view class="template" v-for="(d_item, d_index) in item.msg.data" :key="d_index">
							<text v-if="d_item.type == 'txt'"  class="msg-text" style="float:left;" @tap='goMap' :data-address="item.location.addr" :data-latitude="item.location.lat" :data-longitude="item.location.lng">{{ d_item.data }}</text>
							
							<image  v-if="d_item.type == 'emoji'"
									class="avatar"
									:src="'/static/huanxin/images/faces/' + d_item.data"
									style="width:25px; height:25px; margin:0 0 2px 0; float:left;" />
							
						</view>
						
					</view> 
					
					
			
					
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import audioMsg from "@/comps/chat/msglist/type/audio/audio.vue";
	/*聊天的人*/
	import app from '@/App.vue';
	import {
		GYZJMODEL as gyzjModel
	} from '@/utils/gyzjModel.js';
	let msgStorage = require("../msgstorage");
	let disp = require("../../../utils/broadcast");
	let LIST_STATUS = {
		SHORT: "scroll_view_change",
		NORMAL: "scroll_view"
	};
	let page = 0;
	let Index = 0;
	let curMsgMid = '';
	let isFail = false;
	export default {
		components: {
			audioMsg
		},
		props: {
			username: {
				type: Object,
				value: {},
			},
			reciveScrollTop: {
				type: Object,
				value: {},
			},
		},
		data() {
			return {
				view: LIST_STATUS.NORMAL,
				toView: "",
				chatMsg: [],
				visibility: false,
				userInfo:'',
				/*旧的数据*/
				chatMsgStorage:[],
				historyChatMsgs:[],
				end_count_limit:5,
				add_count:0, 
				// msg_status:0,
			}
		},
		beforeMount(){
			this.visibility = true;
			page = 0;
			Index = 0;
			console.log('页面进来beforeMount');
		},
		beforeDestroy() {
			console.log('页面进来beforeDestroy');
			this.visibility = false;
		},
		created() {
			console.log('页面进来created');
			//app端虽然会触发created，但是读取local storage为空
			// #ifdef H5
			this.create_or_onready();
			// #endif
		},
			
		onShow(){
			
		},
		onLoad(){
			
			console.log('页面进来Onload');
			
		},
		onReady() {
			let userInfo=app.globalData.userInfo;
			this.userInfo=userInfo;
			console.log('页面进来onReady',userInfo);
			// #ifndef H5
			this.create_or_onready();
			// #endif
			
		},
		methods: {
			//地图导航
			goMap: function(e) {
				let data = e.currentTarget.dataset;
				if(data.address){
					console.log('导航的data的值',data);
					let latitude = Number(data.latitude);
					let longitude = Number(data.longitude);
					uni.getLocation({
						type: 'gcj02',
						success: function(res) {
							uni.openLocation({
								latitude: latitude,
								longitude: longitude,
								name: data.name,
								address: data.address,
							})
						}
					})
				}
			},
			/*获取位置*/
			// onPageScroll: function(Object) {
			// 	console.log('msglist的onPageScroll滚动');
			//   console.log(Object.scrollTop);//实时获取到滚动的值
			// },
			handletouchstart:function(){
				 console.log('开始滑动');
			},
			handletouchmove:function(){
				console.log('一直滑动');
				console.log('msglist',this.reciveScrollTop.top);
				var top=this.reciveScrollTop.top;
				console.log('top',top);
				
			},
			handletouchend:function(){
				 console.log('结束滑动');
				 var top=this.reciveScrollTop.top;
				 console.log('top的值',top);
				 if(top<=10){
				 	console.log('执行');
				 	
				 	let me = this;
				 	let username = this.username;
				 	let myUsername = uni.getStorageSync("myUsername");
				 	let sessionKey = username.groupId
				 		? username.groupId + myUsername
				 		: username.your + myUsername;
				 	 
				 	let chatMsg = uni.getStorageSync(sessionKey) || [];
				 	this.renderMsgStorage(null, null, chatMsg, sessionKey);
				 }
			},
			//上滑
			refresh:function(){
				console.log('上滑');
			},
			scrollmore:function(){
				console.log('下滑');
			},
			//分享打开自己的名片
			openCard: function(e) {
				let id=e.currentTarget.dataset.id;
				console.log('aa点击card',id);
				uni.navigateTo({
				  url: '../../../../user-center/my-info/cardcase/cardcase?id='+id,
				}); 
			},
			create_or_onready() {
				let me = this;
				//设置之前消息为空
				// uni.setStorageSync("msg_status",0);
				/*每次显示更新值*/
				uni.setStorageSync("msg_length",0);
				uni.setStorageSync("msg_loading",0);
				/*每次显示更新值*/
				let username = this.username;
				let myUsername = uni.getStorageSync("myUsername");
				let sessionKey = username.groupId
					? username.groupId + myUsername
					: username.your + myUsername;
				
				let chatMsg = uni.getStorageSync(sessionKey) || [];
				console.log('create_or_onready刚进来的chatMsg',chatMsg);
				this.renderMsg(null, null, chatMsg, sessionKey);
				uni.setStorageSync(sessionKey, null);
				
				disp.on('em.xmpp.error.sendMsgErr', function(err) {
					curMsgMid = err.data.mid
					isFail = true
					return
				});
				
				msgStorage.on("newChatMsg", function(renderableMsg, type, curChatMsg, sesskey){
					me.curChatMsg = curChatMsg;
					if(!me.visibility) return;
					// 判断是否属于当前会话
					if(username.groupId){
						// 群消息的 to 是 id，from 是 name
						if(renderableMsg.info.from == username.groupId || renderableMsg.info.to == username.groupId){
							if (sesskey == sessionKey) {
								me.renderMsg(renderableMsg, type, curChatMsg, sessionKey, 'newMsg');
							}
							
						}
					}
					else if(renderableMsg.info.from == username.your || renderableMsg.info.to == username.your){
						if (sesskey == sessionKey) {
							me.renderMsg(renderableMsg, type, curChatMsg, sessionKey, 'newMsg');
						}
					}
				
				});
			},
			normalScroll(){
				this.view = LIST_STATUS.NORMAL
			},
			
			shortScroll(){
				this.view = LIST_STATUS.SHORT
			},
			
			onTap(){
				 console.log('onTap');
				this.$emit('msglistTap');
				// this.triggerEvent("msglistTap", null, { bubbles: true });
			},
			
			previewImage(event){
				var url = event.target.dataset.url;
				uni.previewImage({
					urls: [url]		// 需要预览的图片 http 链接列表
				});
			},
			
			// getHistoryMsg(){
			// 	console.log('getHistoryMsg');
			// 	return;
			// 	let me = this
			// 	let username = this.data.username;
			// 	let myUsername = wx.getStorageSync("myUsername");
			// 	let sessionKey = username.groupId ? username.groupId + myUsername : username.your + myUsername;
			// 	let historyChatMsgs = wx.getStorageSync("rendered_" + sessionKey) || [];
			
			// 	if (Index < historyChatMsgs.length) {
			// 		let timesMsgList = historyChatMsgs.slice(-Index-10, -Index)
			
			// 		this.setData({
			// 			chatMsg: timesMsgList.concat(me.data.chatMsg),
			// 			toView: timesMsgList[timesMsgList.length - 1].mid,
			// 		});
			// 		Index += timesMsgList.length;
			// 		if (timesMsgList.length == 10) {
			// 			page ++
			// 		}
			// 		wx.stopPullDownRefresh()
			// 	}
			// },
			renderMsgStorage(renderableMsg, type, curChatMsg, sessionKey, isnew){
			// 	let me = this;
			// 	var historyChatMsgs=this.historyChatMsgs;
			// 	var end_count_limit=this.end_count_limit;
			// 	if(end_count_limit<historyChatMsgs.length){
			// 		uni.showLoading({
			// 			title: '数据加载中...',
			// 		});
			// 		uni.setStorageSync("msg_status",0);
			// 	}else{
			// 		uni.setStorageSync("msg_status",1);
			// 	}  
			// 	if(this.msg_status==0&&uni.getStorageSync("msg_status")==0){
			// 		this.chatMsgStorage = historyChatMsgs.slice(0,end_count_limit);
			// 		this.toView = historyChatMsgs[historyChatMsgs.length - 1].mid;
			// 		uni.setStorageSync("msg_status",1);
			// 		uni.hideLoading();
			// 	} 
			// 	this.msg_status==1;
			// 	uni.pageScrollTo({
			// 		scrollTop: 0,
			// 	})
			
			// 	if (isFail) {
			// 		this.renderFail(sessionKey)
			// 	}
			this.common_msg_load(5);
			},
			common_msg_load(already_num=4){
				var limit_count=uni.getStorageSync('msg_length');
				var msg_loading=uni.getStorageSync('msg_loading');
				var attr=this.historyChatMsgs;
				var start_length_chu=attr.length;
				console.log('start_length_chu',start_length_chu);
				console.log('already_num',already_num);
				/*加载记录必须大于展示记录*/
				if(start_length_chu>already_num){
					if(msg_loading==0){
						uni.showLoading({
							title: '数据加载中...',
						});
						console.log('limit_count',limit_count);
						
						var end_count_limit=this.end_count_limit;
						
						var start_length_end=attr.length-end_count_limit;
						var start_length_chu_true=attr.length;
						var storage_count=limit_count;
									
						start_length_end-=end_count_limit*storage_count;
						start_length_chu-=end_count_limit*storage_count;
						if(already_num){
							start_length_end-=already_num;
							start_length_chu-=already_num;
						}
						console.log('点击的start_length_end的值',start_length_end);
						console.log('点击的start_length_chu-的值',start_length_chu);
						console.log('点击start_length_chu_true',start_length_chu_true);
						if(start_length_end<0){
							start_length_end=0;
						}
						console.log('attr',attr);
						var arr3=attr.slice(start_length_end,start_length_chu_true);
						var arr4=attr.slice(start_length_end,start_length_chu);
						console.log('arr3的值',arr3);
						// this.chatMsgStorage=arr3;
						// this.toView = arr3[arr3.length - 1].mid;
						var arr5=arr3.slice(0,-5);
						this.chatMsgStorage=arr5;
						this.toView = arr5[arr5.length - 1].mid;
						console.log('arr4的值',arr4);
						
						/*当前截取的记录大于0，并且截取记录必须等于规定的条数*/
						if(arr4.length>0&&arr4.length==end_count_limit){
							limit_count+=1;
							uni.setStorageSync("msg_length",limit_count);
							console.log('有值',arr4);
						}else{
							uni.setStorageSync("msg_loading",1);
							console.log('无值',arr4);
						}
						uni.hideLoading();
					}else{
						console.log('无值，不需再加载',arr4);
						uni.hideLoading();
					}
					uni.pageScrollTo({
						scrollTop: 0,
					})	
					if (isFail) {
						this.renderFail(sessionKey)
					}
				}
			},
			/*新的数据*/
			renderMsg(renderableMsg, type, curChatMsg, sessionKey, isnew,is_concat=0){
				let me = this
				if (curChatMsg.length > 1) {
					this.chatMsg.map(function(elem, index) {
						curChatMsg.map(function(item, i) {
							if(elem.mid == item.mid){
								//me.data.chatMsg.splice(index, 1)
								curChatMsg.splice(i, 1)
							}
						})
					})
				}
				console.log('curChatMsg的值',curChatMsg);
			
				var historyChatMsgs = uni.getStorageSync("rendered_" + sessionKey) || [];
				
				historyChatMsgs = historyChatMsgs.concat(curChatMsg);
			
				// console.log('当前历史',renderableMsg)
				console.log('历史消息', historyChatMsgs)
				if(!historyChatMsgs.length) return;
				console.log('curChatMsg的值',curChatMsg);
				//这里拼接自己的信息进去
				let yourname,userIndex;
				for(var i=0;i<historyChatMsgs.length;i++){
					 yourname=historyChatMsgs[i]['yourname'];
					 userIndex=yourname.slice(yourname.indexOf('gy')+2);
					 (function(i){
						gyzjModel.prototype.getHxDetail(userIndex).then(result => {
							console.log('拼接自己信息进来',result.data);
							// historyChatMsgs[i].userInfo=result.data;
							var data_info=result.data;
							historyChatMsgs[i].avatarUrl=data_info.avatarUrl;
							historyChatMsgs[i].newAvatarUrl=data_info.newAvatarUrl;
						    historyChatMsgs[i].name=data_info.name;
							//var avatar=data_info.newAvatarUrl?data_info.newAvatarUrl:data_info.avatarUrl?data_info.avatarUrl:'/static/allAvatar.png';
							historyChatMsgs[i].username=data_info.name; //设置名称 否则头像文字显示不出
							historyChatMsgs[i].id=data_info.id; //设置名称 否则头像文字显示不出
							// historyChatMsgs[i].yourname=avatar;
						})
					}(i))
				}
				this.historyChatMsgs=historyChatMsgs;
				console.log('最终的历史消息this.historyChatMsgs', this.historyChatMsgs);
				var end_count_limit=-Math.abs(this.end_count_limit);
				if (isnew== 'newMsg') {
					console.log('我是新的消息curChatMsg',curChatMsg);
					console.log('我是新的消息this.chatMsg',this.chatMsg);
					this.chatMsg = this.chatMsg.concat(curChatMsg)
					this.toView = historyChatMsgs[historyChatMsgs.length - 1].mid
				}else{
					console.log('我是老的消息',historyChatMsgs.slice(end_count_limit)); //-10
					// if(is_concat){
					// 	this.chatMsg = historyChatMsgs.slice(-13)
					// }else{
						this.chatMsg = historyChatMsgs.slice(end_count_limit)  //-10
					// }
					this.toView = historyChatMsgs[historyChatMsgs.length - 1].mid   
				}
				console.log('总的消息chatMsg',this.chatMsg);
				console.log('总的消息toView',this.toView);
				uni.setStorageSync("rendered_" + sessionKey, historyChatMsgs);
			
				let chatMsg = uni.getStorageSync(sessionKey) || [];
				chatMsg.map(function(item, index) {
					curChatMsg.map(function(item2, index2) {
						if (item2.mid == item.mid) {
							chatMsg.splice(index, 1)
						}
					})
				})
				
			
				uni.setStorageSync(sessionKey, chatMsg);
				Index = historyChatMsgs.slice(-10).length;
				console.log('sessionKey的值',sessionKey);
				console.log('chatMsg的值',chatMsg);
				console.log('historyChatMsgs的值',Index);
				uni.pageScrollTo({
				  	scrollTop: 9999,
				})
			
				if (isFail) {
					this.renderFail(sessionKey)
				}
			},
			
			renderFail(sessionKey){
				let me = this
				let msgList = me.chatMsg
				msgList.map((item) =>{
					if (item.mid.substring(item.mid.length - 10) == curMsgMid.substring(curMsgMid.length - 10)) {
						item.msg.data[0].isFail = true
						item.isFail = true
						me.chatMsg = msgList
					}
				})
				if (me.curChatMsg[0].mid == curMsgMid) {
					me.curChatMsg[0].msg.data[0].isShow = false;
					me.curChatMsg[0].isShow = false
				}
				uni.setStorageSync("rendered_" + sessionKey, msgList);
				isFail = false
			}
		}
	}
</script>

<style>
	/*.chat-bg{
		position:fixed;
		width: 100%;
		height: 100%;
		z-index: 0;
		top: 50px;
	}*/
	.scroll_view,
	.scroll_view_change {
		/*width: 100%;
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 150rpx;*/
		/* margin-bottom: 174rpx; */
		/*10.3新的下边距*/
		/* margin-bottom: 214rpx; */
		/*10.14新的下边距*/
		margin-bottom: 244rpx; 
		background-color: #FAFAFA;
	}
	
	.scroll_view_X,
	.scroll_view_change_X{
		margin-bottom: 244rpx;
	}
	
	.scroll_view_change {
		/*bottom: 440rpx;*/
		margin-bottom: 590rpx;
	}
	
	.message {
		width: 92%;
		height: auto;
		padding: 0 30rpx;
		position: relative;
	
	}
	
	.time {
		margin: 14rpx 0;
		text-align: center;
	}
	
	.time .time-text {
		display: inline-block;
		padding: 6rpx 20rpx 0 20rpx;
		font-size: 24rpx;
		color: #fff;
		line-height: 28rpx;
		border-radius: 4rpx;
		background-color: #dcdcdc;
	}
	
	.user .user-text {
		margin: auto 100rpx 8rpx;
		font-size: 20rpx;
		color: #dcdcdc;
		display: block;
	}
	
	.avatar {
		width: 72rpx;
		height: 72rpx;
		margin: 0 20rpx 0 0;
		/* border-radius: 6rpx; */
		border-radius: 8rpx;
		float: left;
	}
	
	.msg {
		display: inline-block;
		padding: 20rpx;
		max-width: calc(85% - 80rpx);
		min-height: 40rpx; 
		font-size: 24rpx;
		/*overflow: hidden;*/
		text-align: left;
		word-break: break-all;
		background-color: #fff;
		border-radius: 26rpx;
		position: relative;
		margin-top: 24rpx;
	}
	
	.msg .msg_poprightarrow {
		position: absolute;
		right: -10rpx;
		height: 18rpx;
		width: 18rpx;
		margin-top: -10rpx;
	}
	
	.msg .msg_popleftarrow{
		position:absolute;
		left: -14rpx;
		height: 18rpx;
		width: 18rpx;
		margin-top: -10rpx;
	}
	
	.msg .msg-text {
		line-height: 40rpx;
		font-size: 32rpx;
		margin: 0;
		/*新增black颜色*/
		color:black;
	}
	
	/*.msg:before {
		content: " ";
		position: absolute;
		top: 9px;
		right: 100%;
		border: 6px solid transparent;
		border-right-color: #EDEDED;
	}*/
	
	.self {
		text-align: right;
	}
	
	.self .avatar {
		float: right;
		margin: 0 0 0 20rpx;
	}
	
	.user {
		position: relative;
		bottom: -30rpx;
	}
	
	.self .msg {
		/* background-color: #0873DE; */
		background-color: #96ED6A;
		color: #fff;
	}
	
	.self .msg:before {
		right: inherit;
		left: 100%;
		border-right-color: transparent;
		border-left-color: #b2e281;
	}
	
	.template {
		display: inline;
	}
	.err{
		width: 32rpx;
		height: 32rpx;
		position: absolute;
		left: -40rpx;
	}
	.hide{
		display: none;
	}
	.show{
		display: block;
	}

</style>
